/**
 * ZeusGIS 主应用管理器
 * 统一管理应用的初始化和各个模块的协调
 * @author lucahan <lucahan@foxmail.com>
 */

const { APP_CONFIG } = require('./config/app-config');
const Navigation = require('./components/navigation');
const GeocodingTool = require('./modules/geocoding-tool');
const DataConvertTool = require('./modules/data-convert-tool');
const HelloWorldTool = require('./modules/hello-world-tool');
const Logger = require('./utils/logger');

class ZeusGISApp {
    constructor() {
        this.logger = new Logger('logContainer');
        this.navigation = null;
        this.tools = new Map();
        this.currentTool = null;
        this.welcomeScreen = null;
        
        this.init();
    }

    /**
     * 初始化应用
     */
    init() {
        this.logger.info(`正在启动 ${APP_CONFIG.name} v${APP_CONFIG.version}`);
        
        try {
            // 不再在渲染进程中显示欢迎页面，已在主进程中处理
            this.initializeNavigation();
            this.initializeTools();
            this.bindGlobalEvents();
            this.restoreAppState();
            
            this.logger.success(`${APP_CONFIG.name} 启动成功！`);
        } catch (error) {
            this.logger.error(`应用启动失败: ${error.message}`);
            console.error('App initialization error:', error);
        }
    }

    /**
     * 初始化导航组件
     */
    initializeNavigation() {
        this.navigation = new Navigation();
        this.logger.info('导航组件已初始化');
    }

    /**
     * 初始化工具模块
     */
    initializeTools() {
        try {
            // 初始化地理编码工具
            const geocodingTool = new GeocodingTool();
            this.tools.set('geocoding', geocodingTool);
            this.logger.info('地理编码工具已加载');

            // 初始化数据转换工具
            const dataConvertTool = new DataConvertTool();
            this.tools.set('dataconvert', dataConvertTool);
            this.logger.info('数据转换工具已加载');

            // 初始化示例工具
            const helloWorldTool = new HelloWorldTool();
            this.tools.set('helloworld', helloWorldTool);
            this.logger.info('示例工具已加载');

            this.logger.info(`已加载 ${this.tools.size} 个工具模块`);
        } catch (error) {
            this.logger.error(`工具初始化失败: ${error.message}`);
        }
    }

    /**
     * 绑定全局事件
     */
    bindGlobalEvents() {
        // 监听工具切换事件
        document.addEventListener('toolChange', (event) => {
            this.onToolChange(event.detail);
        });

        // 监听窗口大小变化
        window.addEventListener('resize', () => {
            this.onWindowResize();
        });

        // 监听键盘快捷键
        document.addEventListener('keydown', (event) => {
            this.handleGlobalKeyboard(event);
        });

        // 监听应用关闭前事件
        window.addEventListener('beforeunload', (event) => {
            this.onBeforeUnload(event);
        });

        this.logger.info('全局事件监听器已绑定');
    }

    /**
     * 工具切换事件处理
     * @param {Object} detail - 事件详情
     */
    onToolChange(detail) {
        const { toolId, toolConfig } = detail;
        
        this.currentTool = toolId;
        this.saveAppState();
        
        this.logger.info(`已切换到工具: ${toolConfig.name}`);
    }

    /**
     * 窗口大小变化处理
     */
    onWindowResize() {
        // 响应式布局调整逻辑
        const width = window.innerWidth;
        
        if (width < 768 && this.navigation) {
            // 小屏幕自动隐藏侧边栏
            const sidebar = document.getElementById('sidebar');
            if (sidebar && !sidebar.classList.contains('hidden')) {
                this.navigation.toggleSidebar();
            }
        }
    }

    /**
     * 全局键盘快捷键处理
     * @param {KeyboardEvent} event - 键盘事件
     */
    handleGlobalKeyboard(event) {
        // Ctrl+1-9: 快速切换工具
        if (event.ctrlKey && event.key >= '1' && event.key <= '9') {
            event.preventDefault();
            const toolIndex = parseInt(event.key) - 1;
            this.switchToolByIndex(toolIndex);
        }

        // F1: 显示帮助
        if (event.key === 'F1') {
            event.preventDefault();
            this.showHelp();
        }

        // Esc: 取消当前操作
        if (event.key === 'Escape') {
            this.cancelCurrentOperation();
        }
    }

    /**
     * 根据索引切换工具
     * @param {number} index - 工具索引
     */
    switchToolByIndex(index) {
        const toolIds = ['geocoding', 'dataconvert', 'helloworld'];
        
        if (index < toolIds.length && this.navigation) {
            this.navigation.setActiveTool(toolIds[index]);
        }
    }

    /**
     * 显示帮助信息
     */
    showHelp() {
        const helpContent = `
            <div style="background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; margin: 20px 0;">
                <h3 style="color: #495057; margin-bottom: 15px;">🔧 ZeusGIS 使用帮助</h3>
                <div style="line-height: 1.6;">
                    <h4>快捷键：</h4>
                    <ul>
                        <li><kbd>Ctrl + B</kbd> - 切换侧边栏</li>
                        <li><kbd>Ctrl + 1</kbd> - 切换到地理编码工具</li>
                        <li><kbd>Ctrl + 2</kbd> - 切换到数据转换工具</li>
                        <li><kbd>Ctrl + 3</kbd> - 切换到示例工具</li>
                        <li><kbd>F1</kbd> - 显示帮助</li>
                        <li><kbd>Esc</kbd> - 取消当前操作</li>
                    </ul>
                    <h4>功能说明：</h4>
                    <ul>
                        <li><strong>地理编码转换：</strong>支持Excel文件的批量地理编码转换</li>
                        <li><strong>数据转换：</strong>支持多种地理数据格式之间的转换</li>
                        <li><strong>示例工具：</strong>演示模块，展示如何添加新功能</li>
                    </ul>
                </div>
            </div>
        `;
        
        // 在当前工具面板中显示帮助
        const activePanel = document.querySelector('.tool-panel.active');
        if (activePanel) {
            const helpDiv = document.createElement('div');
            helpDiv.innerHTML = helpContent;
            helpDiv.style.position = 'fixed';
            helpDiv.style.top = '50%';
            helpDiv.style.left = '50%';
            helpDiv.style.transform = 'translate(-50%, -50%)';
            helpDiv.style.zIndex = '9999';
            helpDiv.style.background = 'white';
            helpDiv.style.boxShadow = '0 4px 20px rgba(0,0,0,0.3)';
            helpDiv.style.borderRadius = '8px';
            helpDiv.style.maxWidth = '600px';
            helpDiv.style.maxHeight = '80vh';
            helpDiv.style.overflow = 'auto';
            
            // 添加关闭按钮
            const closeBtn = document.createElement('button');
            closeBtn.textContent = '关闭';
            closeBtn.style.position = 'absolute';
            closeBtn.style.top = '10px';
            closeBtn.style.right = '10px';
            closeBtn.style.background = '#dc3545';
            closeBtn.style.color = 'white';
            closeBtn.style.border = 'none';
            closeBtn.style.borderRadius = '4px';
            closeBtn.style.padding = '5px 10px';
            closeBtn.style.cursor = 'pointer';
            closeBtn.onclick = () => document.body.removeChild(helpDiv);
            
            helpDiv.appendChild(closeBtn);
            document.body.appendChild(helpDiv);
        }
        
        this.logger.info('已显示帮助信息');
    }

    /**
     * 取消当前操作
     */
    cancelCurrentOperation() {
        // 获取当前工具并尝试取消操作
        const currentToolInstance = this.tools.get(this.currentTool);
        
        if (currentToolInstance && typeof currentToolInstance.cancelOperation === 'function') {
            currentToolInstance.cancelOperation();
            this.logger.info('已取消当前操作');
        }
    }

    /**
     * 应用关闭前处理
     * @param {BeforeUnloadEvent} event - 关闭前事件
     */
    onBeforeUnload(event) {
        // 检查是否有正在进行的操作
        const geocodingTool = this.tools.get('geocoding');
        
        if (geocodingTool && geocodingTool.isProcessing) {
            event.preventDefault();
            event.returnValue = '地理编码转换正在进行中，确定要关闭应用吗？';
            return event.returnValue;
        }

        // 保存应用状态
        this.saveAppState();
    }

    /**
     * 保存应用状态
     */
    saveAppState() {
        try {
            const appState = {
                currentTool: this.currentTool,
                sidebarHidden: document.getElementById('sidebar')?.classList.contains('hidden') || false,
                timestamp: Date.now()
            };
            
            localStorage.setItem('zeusgis-app-state', JSON.stringify(appState));
        } catch (error) {
            this.logger.warning(`保存应用状态失败: ${error.message}`);
        }
    }

    /**
     * 恢复应用状态
     */
    restoreAppState() {
        try {
            const savedState = localStorage.getItem('zeusgis-app-state');
            
            if (savedState) {
                const appState = JSON.parse(savedState);
                
                // 恢复当前工具
                if (appState.currentTool && this.navigation) {
                    this.navigation.setActiveTool(appState.currentTool);
                }
                
                // 恢复侧边栏状态
                if (appState.sidebarHidden && this.navigation) {
                    this.navigation.restoreSidebarState();
                }
                
                this.logger.info('应用状态已恢复');
            }
        } catch (error) {
            this.logger.warning(`恢复应用状态失败: ${error.message}`);
        }
    }

    /**
     * 获取工具实例
     * @param {string} toolId - 工具ID
     * @returns {Object|null} 工具实例
     */
    getTool(toolId) {
        return this.tools.get(toolId) || null;
    }

    /**
     * 获取应用信息
     * @returns {Object} 应用信息
     */
    getAppInfo() {
        return {
            ...APP_CONFIG,
            currentTool: this.currentTool,
            loadedTools: Array.from(this.tools.keys()),
            uptime: Date.now() - this.startTime
        };
    }

    /**
     * 重启应用
     */
    restart() {
        this.logger.info('正在重启应用...');
        
        // 清理资源
        this.cleanup();
        
        // 重新初始化
        setTimeout(() => {
            this.init();
        }, 100);
    }



    /**
     * 清理资源
     */
    cleanup() {
        // 清理工具实例
        this.tools.clear();
        
        // 移除事件监听器
        document.removeEventListener('toolChange', this.onToolChange);
        window.removeEventListener('resize', this.onWindowResize);
        
        // 清理欢迎页面
        if (this.welcomeScreen && this.welcomeScreen.parentNode) {
            this.welcomeScreen.parentNode.removeChild(this.welcomeScreen);
            this.welcomeScreen = null;
        }
        
        this.logger.info('应用资源已清理');
    }
}

// 导出应用类
module.exports = ZeusGISApp;